package com.web.exiaodao.remote.service.impl;

import com.alibaba.fastjson.JSON;
import com.web.exiaodao.business.constant.JConstant;
import com.web.exiaodao.business.entity.*;
import com.web.exiaodao.business.repository.FanliOrderRepository;
import com.web.exiaodao.business.repository.UserRepository;
import com.web.exiaodao.business.repository.WalletTradeRecordRepository;
import com.web.exiaodao.business.repository.WalletWithdrawRecordRepository;
import com.web.exiaodao.remote.service.ApiConfigurationTableService;
import com.web.exiaodao.remote.service.ApiUserService;
import com.web.exiaodao.remote.service.ApiWalletTradeRecordService;
import com.web.exiaodao.remote.vo.*;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.util.DateUtils;
import com.web.webstart.base.util.MathUtils;
import com.web.webstart.base.util.ReflectionUtils;
import com.web.webstart.base.util.XaUtil;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.result.XaResult;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: zhangl
 * @times: 2017-01-22 18:34:39
 * 类的说明：前端APIWalletTradeRecord接口实现类
 **/
@Service("ApiWalletTradeRecordService")
@Transactional(readOnly = false)
public class ApiWalletTradeRecordServiceImpl extends BaseService<WalletTradeRecord> implements ApiWalletTradeRecordService {

    private static final Logger LOGGER = Logger.getLogger(ApiWalletTradeRecordServiceImpl.class);

    @Autowired
    private WalletTradeRecordRepository walletTradeRecordRepository;
    @Autowired
    private ApiUserService userService;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private WalletWithdrawRecordRepository walletWithdrawRecordRepository;
    @Autowired
    private ApiConfigurationTableService configurationTableService;
    @Autowired
    FanliOrderRepository fanliOrderRepository;

    @Override
    public XaResult<WalletTradeRecordVo> findOne(Long tId) throws BusinessException {
        WalletTradeRecord obj = walletTradeRecordRepository.findByIdAndStatusNot(tId, XaConstant.Status.delete);
        XaResult<WalletTradeRecordVo> xr = new XaResult<WalletTradeRecordVo>();
        if (XaUtil.isNotEmpty(obj)) {
            xr.setObject(JSON.parseObject(JSON.toJSONString(obj), WalletTradeRecordVo.class));
            xr.getObject().setId(obj.getId());
            LOGGER.info("查询单个实体----->WalletTradeRecord");
        } else {
            xr.error(XaConstant.Message.object_not_find);
            LOGGER.info(XaConstant.Message.object_not_find);
            throw new BusinessException(XaConstant.Message.object_not_find);
        }
        return xr;
    }

    @Override
    public XaResult<List<WalletTradeRecordVo>> findListNEStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable)
            throws BusinessException {
        Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
        if (status == null) {// 默认显示非删除的所有数据
            status = XaConstant.Status.delete;
        }
        filters.put("status", new SearchFilter("status", Operator.NE, status));
        Page<WalletTradeRecord> page = walletTradeRecordRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), WalletTradeRecord.class), pageable);
        XaResult<List<WalletTradeRecordVo>> xr = new XaResult<List<WalletTradeRecordVo>>();
        xr.setObject(JSON.parseArray(JSON.toJSONString(page.getContent()), WalletTradeRecordVo.class));
        for (int i = 0; i < page.getContent().size(); i++) {
            xr.getObject().get(i).setId(page.getContent().get(i).getId());
        }
        return xr;
    }

    @Override
    public XaResult<List<WalletTradeRecordVo>> findListEQStatusByFilter(
            Integer status, Map<String, Object> filterParams, Pageable pageable)
            throws BusinessException {
        Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
        if (status == null) {// 默认显示正常数据
            status = XaConstant.Status.valid;
        }
        filters.put("status", new SearchFilter("status", Operator.EQ, status));
        Page<WalletTradeRecord> page = walletTradeRecordRepository.findAll(DynamicSpecifications
                .bySearchFilter(filters.values(), WalletTradeRecord.class), pageable);
        XaResult<List<WalletTradeRecordVo>> xr = new XaResult<List<WalletTradeRecordVo>>();
        xr.setObject(JSON.parseArray(JSON.toJSONString(page.getContent()), WalletTradeRecordVo.class));
        for (int i = 0; i < page.getContent().size(); i++) {
            xr.getObject().get(i).setId(page.getContent().get(i).getId());
        }
        return xr;
    }

    @Override
    public XaResult<WalletTradeRecordVo> multiOperate(String modelIds,
                                                      Integer status) throws BusinessException {
        XaResult<WalletTradeRecordVo> xr = new XaResult<WalletTradeRecordVo>();
        if (status == null) {
            status = XaConstant.Status.delete;
        }
        if (modelIds != null) {
            String[] ids = modelIds.split(",");
            for (String id : ids) {
                WalletTradeRecord obj = walletTradeRecordRepository.findByIdAndStatusNot(Long.parseLong(id), status);
                if (XaUtil.isNotEmpty(obj)) {
                    obj.setStatus(status);
                    obj = walletTradeRecordRepository.save(obj);
                    xr.setObject(JSON.parseObject(JSON.toJSONString(obj), WalletTradeRecordVo.class));
                    xr.getObject().setId(obj.getId());
                }
            }
        }
        LOGGER.info("更改数据状态----->WalletTradeRecord");
        return xr;
    }

    @Override
    public XaResult<WalletTradeRecordVo> createModel(WalletTradeRecord model)
            throws BusinessException {
        XaResult<WalletTradeRecordVo> xr = new XaResult<WalletTradeRecordVo>();
        WalletTradeRecord obj = walletTradeRecordRepository.save(model);
        xr.setObject(JSON.parseObject(JSON.toJSONString(obj), WalletTradeRecordVo.class));
        xr.getObject().setId(obj.getId());
        LOGGER.info("新增数据成功----->WalletTradeRecord");
        return xr;
    }

    @Override
    public XaResult<WalletTradeRecordVo> updateModel(WalletTradeRecord model)
            throws BusinessException {
        WalletTradeRecord obj = walletTradeRecordRepository.findOne(model.getId());
        XaResult<WalletTradeRecordVo> xr = new XaResult<WalletTradeRecordVo>();
        if (XaUtil.isNotEmpty(obj)) {
            obj.setUserId(XaUtil.isNotEmpty(model.getUserId()) ? model.getUserId() : obj.getUserId());
            obj.setMoney(XaUtil.isNotEmpty(model.getMoney()) ? model.getMoney() : obj.getMoney());
            obj.setTradeType(XaUtil.isNotEmpty(model.getTradeType()) ? model.getTradeType() : obj.getTradeType());
            obj.setIncomeExpendType(XaUtil.isNotEmpty(model.getIncomeExpendType()) ? model.getIncomeExpendType() : obj.getIncomeExpendType());
            obj.setIncomeExpendMethod(XaUtil.isNotEmpty(model.getIncomeExpendMethod()) ? model.getIncomeExpendMethod() : obj.getIncomeExpendMethod());
            obj.setRemarks(XaUtil.isNotEmpty(model.getRemarks()) ? model.getRemarks() : obj.getRemarks());
            obj.setTradeOrderNo(XaUtil.isNotEmpty(model.getTradeOrderNo()) ? model.getTradeOrderNo() : obj.getTradeOrderNo());
            obj.setTradeStatus(XaUtil.isNotEmpty(model.getTradeStatus()) ? model.getTradeStatus() : obj.getTradeStatus());
            obj.setAccountBalance(XaUtil.isNotEmpty(model.getAccountBalance()) ? model.getAccountBalance() : obj.getAccountBalance());
            obj.setTradeCloseDateTime(XaUtil.isNotEmpty(model.getTradeCloseDateTime()) ? model.getTradeCloseDateTime() : obj.getTradeCloseDateTime());
            obj = walletTradeRecordRepository.save(obj);
            xr.setObject(JSON.parseObject(JSON.toJSONString(obj), WalletTradeRecordVo.class));
            xr.getObject().setId(obj.getId());
        } else {
            xr.error(XaConstant.Message.object_not_find);
        }
        LOGGER.info("编辑数据成功----->WalletTradeRecord");
        return xr;
    }


    /**
     * 钱包支付成功
     */
    @Override
    public XaResult<WalletTradeRecordVo> walletPaySucessSaveRecord(UserVo userVo, Order order) throws BusinessException {
        XaResult<WalletTradeRecordVo> xr = new XaResult<>();
        //钱包支付 修改订单 1：账号余额修改 2：钱包交易记录增加
        //钱包支付
        String price = order.getGoodsTotalPrices() + "";
        String orderNo = order.getOrderNo();
        Double balance = userVo.getBalance();
        if (XaUtil.getNutNullDouble(price, 0) > balance) {
            throw new BusinessException("钱包支付失败，余额不足！");
        }
        double userBalance = MathUtils.sub(balance, XaUtil.getNutNullDouble(price, 0));
        userVo.setBalance(userBalance);
        userService.updateModel(JSON.parseObject(JSON.toJSONString(userVo), User.class));

        WalletTradeRecord wallet = new WalletTradeRecord();
        wallet.setUserId(userVo.getId());
        wallet.setMoney(XaUtil.getNutNullDouble(price, 0));
        wallet.setTradeType(JConstant.WalletTradeType.WALLET_TRADE_CONSUME);
        wallet.setIncomeExpendType(-1);
        wallet.setIncomeExpendMethod(0);
        wallet.setRemarks(orderNo + "-" + "钱包支付成功");
        wallet.setTradeOrderNo(orderNo);
        wallet.setTradeStatus(JConstant.WalletTradeStatus.TRADE_SUCESS);
        wallet.setAccountBalance(userVo.getBalance());
        wallet.setCreateTime(DateUtils.getToDayStr());
        wallet = walletTradeRecordRepository.save(wallet);

        xr.setObject(JSON.parseObject(JSON.toJSONString(wallet), WalletTradeRecordVo.class));

        LOGGER.info("钱包支付成功----->walletPaySucessSaveRecord");

        return xr;
    }

    /**
     * 钱包退款成功
     */
    @Override
    public XaResult<WalletTradeRecordVo> walletPayRefundSaveRecord(UserVo userVo, Order order) throws BusinessException {
        XaResult<WalletTradeRecordVo> xr = new XaResult<>();
        //钱包支付退款  1：账号余额修改 2：钱包交易记录增加
        //钱包支付
        String price = order.getGoodsTotalPrices() + "";
        String orderNo = order.getOrderNo();
        Double balance = userVo.getBalance();

        double userBalance = MathUtils.add(balance, XaUtil.getNutNullDouble(price, 0));
        userVo.setBalance(userBalance);
        userService.updateModel(JSON.parseObject(JSON.toJSONString(userVo), User.class));

        WalletTradeRecord wallet = new WalletTradeRecord();
        wallet.setUserId(userVo.getId());
        wallet.setMoney(NumberUtils.createDouble(price));
        wallet.setTradeType(JConstant.WalletTradeType.WALLET_TRADE_CONSUME_REFUND);
        wallet.setIncomeExpendType(+1);
        wallet.setIncomeExpendMethod(0);
        wallet.setRemarks(orderNo + "-" + "钱包退款成功");
        wallet.setTradeOrderNo(orderNo);
        wallet.setTradeStatus(JConstant.WalletTradeStatus.TRADE_SUCESS);
        wallet.setAccountBalance(userVo.getBalance());
        wallet.setCreateTime(DateUtils.getToDayStr());
        wallet = walletTradeRecordRepository.save(wallet);

        xr.setObject(JSON.parseObject(JSON.toJSONString(wallet), WalletTradeRecordVo.class));

        LOGGER.info("钱包退款成功----->walletPayRefundSaveRecord");

        return xr;
    }

    /**
     * 钱包充值成功
     *
     * @return
     * @throws BusinessException
     */
    @Override
    public XaResult<WalletTradeRecordVo> rechargeSucessSaveRecord(Double price, User userVo, WalletRechargeRecord order) throws BusinessException {

        XaResult<WalletTradeRecordVo> xr = new XaResult<>();

        Double balance = userVo.getBalance();
        double userBalance = MathUtils.add(balance, price);
        userVo.setBalance(userBalance);
        userService.updateModel(JSON.parseObject(JSON.toJSONString(userVo), User.class));

        WalletTradeRecord wallet = new WalletTradeRecord();
        wallet.setUserId(userVo.getId());
        wallet.setMoney(order.getRechargeMoney());
        wallet.setTradeType(JConstant.WalletTradeType.WALLET_TRADE_RECHARGE);
        wallet.setIncomeExpendType(+1);
        wallet.setIncomeExpendMethod(1);
        wallet.setRemarks(order.getRechargeOrderNo() + "-" + "钱包充值成功");
        wallet.setTradeOrderNo(order.getRechargeOrderNo());
        wallet.setTradeStatus(JConstant.WalletTradeStatus.TRADE_SUCESS);
        wallet.setAccountBalance(userVo.getBalance());
        wallet.setCreateTime(DateUtils.getToDayStr());
        wallet = walletTradeRecordRepository.save(wallet);

        xr.setObject(JSON.parseObject(JSON.toJSONString(wallet), WalletTradeRecordVo.class));

        LOGGER.info("钱包余额充值成功----->rechargeSucessSaveRecord");

        return xr;
    }

    /**
     * 钱包提现申请中
     * 1:用户账户余额fix
     * 2：交易记录添加
     * 3: 提现记录增加
     */
    @Override
    public XaResult<WalletWithdrawRecordVo> widthdrawApplyForring(WalletWithdrawRecord model) throws BusinessException {
        XaResult<WalletWithdrawRecordVo> xr = new XaResult<>();

        //1:用户账户余额fix
        long userId = model.getUserId();
        XaResult<UserVo> userXr = userService.findOne(userId);
        double balance = userXr.getObject().getBalance();
        double withdrawMoney = model.getWithdrawMoney();
        double userBalance = MathUtils.sub(balance, withdrawMoney);
        userXr.getObject().setBalance(userBalance);//设置余额
        userXr.getObject().setAlipayAccount(model.getAipayAccount());//保存用户的最后使用的一个支付宝账号
        userXr = userService.updateModel(JSON.parseObject(JSON.toJSONString(userXr.getObject()), User.class));

        //3:提现记录增加
        WalletWithdrawRecord obj = walletWithdrawRecordRepository.save(model);
        xr.setObject(JSON.parseObject(JSON.toJSONString(obj), WalletWithdrawRecordVo.class));

        //2:交易记录添加
        WalletTradeRecord wallet = new WalletTradeRecord();
        wallet.setUserId(userId);
        wallet.setMoney(model.getWithdrawMoney());
        wallet.setTradeType(JConstant.WalletTradeType.WALLET_TRADE_WITHDRAW);
        wallet.setIncomeExpendType(-1);
        wallet.setIncomeExpendMethod(1);
        wallet.setRemarks(obj.getWithdrawTradeNo() + "-" + "提现申请中");
        wallet.setTradeOrderNo(obj.getWithdrawTradeNo());
        wallet.setTradeStatus(JConstant.WalletTradeStatus.TRADE_ING);//1：交易进行中（提现需要时间）
        wallet.setAccountBalance(userXr.getObject().getBalance());
        wallet.setCreateTime(DateUtils.getToDayStr());
        wallet = walletTradeRecordRepository.save(wallet);

        return xr;
    }

    /**
     * 钱包提现失败
     * 1:用户账户余额fix 钱数返还
     * 2：交易记录添加  (1)状态改变 (2):交易完成/关闭时间改变
     */
    @Override
    public XaResult<WalletTradeRecordVo> widthdrawFail(String walletWithdrawRecordFlowId, String errorMsg) throws BusinessException {
        XaResult<WalletTradeRecordVo> xr = new XaResult<>();

        //提现信息
        WalletWithdrawRecord model = walletWithdrawRecordRepository.findByWithdrawTradeNoAndStatusNot(walletWithdrawRecordFlowId, XaConstant.Status.delete);
        if (model == null) {
            xr.error("提现记录流水号不存在(" + walletWithdrawRecordFlowId + ")!!!");
            LOGGER.info(xr.getMessage());
            return xr;
        }
        if (model.getWithdrawStatus() != JConstant.WalletWithdrawStatus.WITHDRAW_ING.intValue()) {
            return xr;
        }
        model.setWithdrawStatus(JConstant.WalletWithdrawStatus.WITHDRAW_CLOSE);
        model.setWithdrawSucessTime(DateUtils.getToday(DateUtils.YYYYMMDDHHMMSS));
        model.setRemark(errorMsg);//提现失败的原因
        model = walletWithdrawRecordRepository.save(model);

        //用户信息
        long userId = model.getUserId();
        XaResult<UserVo> userXr = userService.findOne(userId);
        Double balance = userXr.getObject().getBalance();
        double userBalance = MathUtils.add(balance, model.getWithdrawMoney());
        userXr.getObject().setBalance(userBalance);//设置余额
        userService.updateModel(JSON.parseObject(JSON.toJSONString(userXr.getObject()), User.class));

        //交易记录信息
        List<WalletTradeRecord> walletTradeRecords = walletTradeRecordRepository.findByTradeOrderNo(model.getWithdrawTradeNo());
        if (XaUtil.isEmpty(walletTradeRecords)) {
            throw new BusinessException(XaConstant.Message.object_not_find);
        }
        WalletTradeRecord walletTradeRecord = walletTradeRecords.get(0);
        walletTradeRecord.setTradeCloseDateTime(DateUtils.getToday(DateUtils.YYYYMMDDHHMMSS));
        walletTradeRecord.setTradeStatus(JConstant.WalletTradeStatus.TRADE_CLOSE);
        walletTradeRecord.setRemarks(walletTradeRecord.getTradeOrderNo() + "-" + "提现关闭");
        walletTradeRecord = walletTradeRecordRepository.save(walletTradeRecord);
        LOGGER.info("fix 完成....");

        //交易失败新增交易记录
        WalletTradeRecord newWallet = new WalletTradeRecord();
        newWallet.setUserId(userId);
        newWallet.setMoney(model.getWithdrawMoney());
        newWallet.setTradeType(JConstant.WalletTradeType.WALLET_TRADE_WITHDRAW_REUND);
        newWallet.setIncomeExpendType(+1);
        newWallet.setIncomeExpendMethod(0);
        newWallet.setRemarks(model.getWithdrawTradeNo() + "-" + "提现关闭退款");
        newWallet.setTradeOrderNo(model.getWithdrawTradeNo());
        newWallet.setTradeStatus(JConstant.WalletTradeStatus.TRADE_CLOSE);//1：交易进行中（提现需要时间）
        newWallet.setAccountBalance(userXr.getObject().getBalance());
        newWallet.setCreateTime(DateUtils.getToDayStr());
        newWallet.setTradeCloseDateTime(DateUtils.getToday(DateUtils.YYYYMMDDHHMMSS));
        newWallet = walletTradeRecordRepository.save(newWallet);
        LOGGER.info("保存 完成...." + newWallet.getId());

        xr.setObject(JSON.parseObject(JSON.toJSONString(walletTradeRecord), WalletTradeRecordVo.class));
        return xr;
    }

    /**
     * 钱包提现成功
     * 1：交易记录fix (1)状态改变 (2):交易完成时间改变
     */
    @Override
    public XaResult<WalletTradeRecordVo> widthdrawSucess(String walletWithdrawRecordFlowId) throws BusinessException {
        XaResult<WalletTradeRecordVo> xr = new XaResult<>();

        //提现信息
        WalletWithdrawRecord model = walletWithdrawRecordRepository.findByWithdrawTradeNoAndStatusNot(walletWithdrawRecordFlowId, XaConstant.Status.delete);
        if (model == null) {
            xr.error("提现记录流水号不存在(" + walletWithdrawRecordFlowId + ")!");
            LOGGER.info(xr.getMessage());
            return xr;
        }
        if (model.getWithdrawStatus() != JConstant.WalletWithdrawStatus.WITHDRAW_ING.intValue()) {
            return xr;
        }
        model.setWithdrawStatus(JConstant.WalletWithdrawStatus.WITHDRAW_SUCESS);
        model.setWithdrawSucessTime(DateUtils.getToday(DateUtils.YYYYMMDDHHMMSS));
        model = walletWithdrawRecordRepository.save(model);

        //交易记录信息
        List<WalletTradeRecord> walletTradeRecords = walletTradeRecordRepository.findByTradeOrderNo(model.getWithdrawTradeNo());
        if (XaUtil.isEmpty(walletTradeRecords)) {
            throw new BusinessException(XaConstant.Message.object_not_find);
        }
        WalletTradeRecord walletTradeRecord = walletTradeRecords.get(0);
        walletTradeRecord.setTradeCloseDateTime(DateUtils.getToday(DateUtils.YYYYMMDDHHMMSS));
        walletTradeRecord.setTradeStatus(JConstant.WalletTradeStatus.TRADE_SUCESS);
        walletTradeRecord.setRemarks(walletTradeRecord.getTradeOrderNo() + "-" + "提现完成");
        walletTradeRecord = walletTradeRecordRepository.save(walletTradeRecord);

        xr.setObject(JSON.parseObject(JSON.toJSONString(walletTradeRecord), WalletTradeRecordVo.class));
        return xr;
    }

    /**
     * 每笔订单都完成后的15天都会计算推荐自己注册的这个人获取的收益
     * <p>
     * //1:获取所有的订单完成时间>=15天并且没有计算过首页的订单
     * //2:获取一级分销和二级分销的收益比例：订单支付金额*收益比例
     * //3:获取该订单对应的一级分销人和二级分销的人
     * //4:收益表写入收益记录
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void autoCalculateEarnings(Order order, ConfigurationTableVo configurationTableVo) throws Exception {
        /**
         *
         * # SELECT user_id, order_no, order_state, order_sucess_date_time FROM tb_xa_order orders WHERE order_state = 4 AND order_type != 2 AND date_add(orders.order_sucess_date_time,interval 15 day) <= now();

         # SELECT distribution1rate, distribution2rate FROM tb_xa_configurationtable LIMIT 0,1;

         # SELECT *
         # FROM (
         #        SELECT id, mobile, recommend_phone, 1 AS LEVEL
         #        FROM `tb_xa_user`
         #        WHERE recommend_phone = '18049531390' AND STATUS <> 3
         #      ) t1
         # UNION
         # SELECT id,  mobile, recommend_phone , 2 AS LEVEL
         # FROM `tb_xa_user`
         # WHERE recommend_phone IN (
         #   SELECT mobile
         #   FROM `tb_xa_user`
         #   WHERE recommend_phone = '18049531390'
         # ) AND STATUS <> 3

         # INSERT INTO tb_xa_wallettraderecord
         # (create_time, create_user, account_balance, income_expend_method, income_expend_type, money, remarks, trade_order_no, trade_status, trade_type, user_id, trade_close_date_time)
         # VALUES
         #   (now(), 'sys', 9999999, 0, 1, 99999.99, '佣金收入', 111000000, 0, 4, 9999999, now());
         */

//    存储过程有问题，双层while
//    CREATE PROCEDURE `pro_autoCalculateEarnings`() COMMENT '计算佣金收益 超过15天 计算佣金收益;days提前天数，默认15'
//    BEGIN
//    DECLARE  no_more_record INT DEFAULT 0;
//    -- 定义变量
//    DECLARE userId BIGINT;-- 用户id
//    DECLARE orderNo VARCHAR(50);-- 订单No
//    DECLARE price DOUBLE;-- 订单价格
//
//    DECLARE distribution1rateTemp DOUBLE;-- 1级分销收益比例
//    DECLARE distribution2rateTemp DOUBLE;-- 2级分销收益比例
//
//    DECLARE userinfo_userId BIGINT;
//    DECLARE userinfo_mobile VARCHAR(11);
//    DECLARE userinfo_recommendPhone VARCHAR(11);
//    DECLARE userinfo_level int;
//    DECLARE userinfo_balance DOUBLE;
//    DECLARE userinfo_noMoreRecord int DEFAULT 0;
//
//
//    -- 定义游标
//
//    -- 1：外层循环订单
//    DECLARE orders_cur CURSOR FOR  SELECT user_id, order_no, order_total_pirce FROM tb_xa_order orders WHERE order_state = 4 AND order_type != 2 AND date_add(order_sucess_date_time,interval 15 day) <= now();
//
//    -- 如果没有记录游标设置为1
//    DECLARE CONTINUE HANDLER FOR NOT FOUND  SET  no_more_record = 1;
//
//    -- 配置表信息
//    SELECT distribution1rate, distribution2rate
//    INTO   distribution1rateTemp, distribution2rateTemp
//    FROM tb_xa_configurationtable WHERE status <> 3  LIMIT 0,1;
//
//    -- 循环游标
//    WHILE no_more_record != 1 DO
//
//      -- ///////////////////////////
//              -- 2：内层循环用户
//    DECLARE user_cur CURSOR FOR
//    SELECT *
//    FROM (
//            SELECT id, mobile, recommend_phone, 1 AS LEVEL, balance
//            FROM `tb_xa_user`
//                    WHERE recommend_phone = userId AND STATUS <> 3
//    ) t1
//    UNION
//    SELECT id,  mobile, recommend_phone , 2 AS LEVEL,balance
//    FROM `tb_xa_user`
//    WHERE recommend_phone IN (
//            SELECT mobile
//          FROM `tb_xa_user`
//                  WHERE recommend_phone = userId
//    ) AND STATUS <> 3
//    ;
//    DECLARE  CONTINUE HANDLER FOR NOT FOUND  SET  userinfo_noMoreRecord = 1;
//    OPEN user_cur;
//    FETCH user_cur INTO userinfo_userId, userinfo_mobile, userinfo_recommendPhone,userinfo_level,userinfo_balance;
//    WHILE userinfo_noMoreRecord != 1 DO
//        -- 保存记录 start
//    IF userinfo_level = 1 THEN
//    INSERT INTO tb_xa_wallettraderecord
//            (create_time, create_user, account_balance, income_expend_method, income_expend_type, money, remarks, trade_order_no, trade_status, trade_type, user_id, trade_close_date_time)
//    VALUES
//            (now(),
//              'sys',
//    userinfo_balance+price*distribution1rateTemp, -- 账号余额
//              0, 1,
//    price*distribution1rateTemp,
//            '佣金收入',
//    orderNo,
//            0, 4,
//    userinfo_userId,
//    now());
//    ELSEIF userinfo_level = 2 THEN
//    INSERT INTO tb_xa_wallettraderecord
//            (create_time, create_user, account_balance, income_expend_method, income_expend_type, money, remarks, trade_order_no, trade_status, trade_type, user_id, trade_close_date_time)
//    VALUES
//            (now(),
//              'sys',
//    userinfo_balance+price*distribution2rateTemp, -- 账号余额
//              0, 1,
//    price*distribution2rateTemp,
//            '佣金收入',
//    orderNo,
//            0, 4,
//    userinfo_userId,
//    now());
//    END IF;
//        -- 保存记录 end
//    FETCH user_cur INTO userinfo_userId, userinfo_mobile, userinfo_recommendPhone,userinfo_level,userinfo_balance;
//    END WHILE;
//    CLOSE user_cur;
//
//      -- ///////////////////////////
//              -- 将下一条记录赋值给变量
//    FETCH orders_cur INTO userId, orderNo, price;
//    END WHILE;
//    -- 关闭游标exiaodao
//    CLOSE orders_cur;
//    END

        double rate1 = configurationTableVo.getDistribution1Rate();
        double rate2 = configurationTableVo.getDistribution2Rate();

        long userId = order.getUserId();
        UserVo userVo = null;
        try {
            userVo = userService.findOne(userId).getObject();
        } catch (BusinessException e) {
            e.printStackTrace();
            return;
        }
        if (XaUtil.isEmpty(userVo.getMobile())) {
            return;
        }
        if (XaUtil.isEmpty(userVo.getRecommendPhone())) {
            return;
        }

        List<UserVo> users = new ArrayList<>();
        User user1 = userRepository.findTopByMobileAndStatusNot(userVo.getRecommendPhone(), XaConstant.Status.delete);//一级推荐人
        if (user1 == null) {
            return;
        }
        UserVo userVo1 = JSON.parseObject(JSON.toJSONString(user1), UserVo.class);
        userVo1.setLevel(1);
        users.add(userVo1);
        User user2 = null;//二级推荐人
        if (XaUtil.isNotEmpty(user1.getRecommendPhone())) {
            user2 = userRepository.findTopByMobileAndStatusNot(user1.getRecommendPhone(),XaConstant.Status.delete);
        }
        if (user2 != null) {
            UserVo userVo2 = JSON.parseObject(JSON.toJSONString(user2), UserVo.class);
            userVo2.setLevel(2);
            users.add(userVo2);
        }
        List<WalletTradeRecord> recordsFinal = new ArrayList();
        for (UserVo user : users) {//最多size=2
            long userIdTemp = user.getId();
            Double price = order.getOrderTotalPirce();
            Double rjbalance = MathUtils.mul(price, (user.getLevel() == 1 ? rate1 : rate2));//佣金
            Double rjBalance2 = rjbalance < 0.01 ? 0 : MathUtils.round(rjbalance, 2);
            Double userBalance = MathUtils.add(user.getBalance(), rjBalance2);
            //保存用户信息
            user.setBalance(userBalance);
            User userTemp = JSON.parseObject(JSON.toJSONString(user), User.class);
            userService.updateModel(userTemp);

            //保存收益信息
            WalletTradeRecord record = new WalletTradeRecord();
            record.setCreateTime(DateUtils.getToDayStr());
            record.setCreateUser("sys");
            record.setAccountBalance(userBalance);
            record.setIncomeExpendMethod(0);
            record.setIncomeExpendType(1);
            record.setMoney(rjbalance);
            record.setRemarks(ReflectionUtils.getContantName(JConstant.WalletTradeType.class, JConstant.WalletTradeType.WALLET_TRADE_COMMISSION) + ";"  //佣金分成
                    + (user.getLevel()==1?"一级":"二级") + ";" +  //级别
                    "消费人;"+userId + "(" + userVo.getUserName() + ");" +
                    "消费金额:"+order.getOrderTotalPirce()+
                    "分成比例:"+(user.getLevel()==1?rate1:rate2)+
                    ";佣金收入:" + rjbalance);//佣金收入
            record.setTradeOrderNo(order.getOrderNo());
            record.setTradeStatus(JConstant.WalletTradeStatus.TRADE_SUCESS);
            record.setTradeType(JConstant.WalletTradeType.WALLET_TRADE_COMMISSION);
            record.setUserId(userIdTemp);
            record.setTradeCloseDateTime(DateUtils.getToDayStr());
            recordsFinal.add(record);
        }

        walletTradeRecordRepository.save(recordsFinal);

        LOGGER.info("ok.....");
    }

    /**
     * 返利订单完成
     * @see ApiFanliOrderServiceImpl
     */
    public XaResult<FanliOrderVo> fanliOrderSucess(FanliOrder fanliOrder, User user) throws Exception {
        XaResult<FanliOrderVo> xr = new XaResult<>();

        //1:用户账户余额fix
        double balance = user.getBalance();
        double withdrawMoney = fanliOrder.getFanliMoney();
        double userBalance = MathUtils.sub(balance, withdrawMoney);
        user.setBalance(userBalance);//设置余额
        userRepository.save(user);

        //2:交易记录添加
        WalletTradeRecord wallet = new WalletTradeRecord();
        wallet.setUserId(user.getId());
        wallet.setMoney(fanliOrder.getFanliMoney());
        wallet.setTradeType(JConstant.WalletTradeType.WALLET_TRADE_FANLI);
        wallet.setIncomeExpendType(1);
        wallet.setIncomeExpendMethod(0);
        wallet.setRemarks(fanliOrder.getOrderNo() + "-" + "返利订单完成");
        wallet.setTradeOrderNo(fanliOrder.getOrderNo());
        wallet.setTradeStatus(JConstant.WalletTradeStatus.TRADE_SUCESS);//1：交易进行中（提现需要时间）
        wallet.setAccountBalance(user.getBalance());
        wallet.setCreateTime(DateUtils.getToDayStr());
        wallet = walletTradeRecordRepository.save(wallet);

        fanliOrder.setFaliOrderStatus(JConstant.FanliOrderStatus.HAVING_FANLI_ORDER+"");
        fanliOrder =  fanliOrderRepository.save(fanliOrder);
        xr.setObject(JSON.parseObject(JSON.toJSONString(fanliOrder), FanliOrderVo.class));

        return xr;
    }

}
